<script setup>
import { ref, reactive, onMounted, watch, nextTick, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { departmentApi as MainApi, departmentById as MainById, iuserApi } from '@T2/service/api.ts';
import { useIuserInfoStore, useCurrentWatchStore } from '@T2/store/users.ts';
import { buildTree } from '@T2/utils/utils.ts';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { info, getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['304', '305', '306']);

onMounted(() => {
  GetMainTable();
  getIuserList();
});

const MainTable = reactive({
  data: [],
  iuserList: [],
});
const Filter = reactive({
  page: 1,
  ordering: 'create_time',
  search: '',
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainTable.data = [];
  MainApi({
    method: 'get',
    params: {
      ...Filter,
    }
  }).then(res => {
    const tree = buildTree(res?.results || [], 'parent');
    MainTable.data = [{ id: 0, name: curProject.name, parent: null, children: tree }];
  });
}
const getIuserList = (text = '') => {
  iuserApi({
    method: 'get',
    params: {
      search: text,
      projects: curProject.id,
      noProject: true,
    },
  }).then(res => {
    let { results, count } = res || { results: [], count: 0};
    MainTable.iuserList = results;
  }).catch(e => {
    reject(e);
  });
}

/* 新增编辑 */
const MainPopup = reactive({
  visible: false,
  type: '新增',
});
const MainForm = reactive({
  model: {},
});
const MainFormRef = ref(null);
const handleMainAdd = (isAble = false, row = {}) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '新增';
  MainForm.model = {
    parent: row.id || null,
  };
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainEdit = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '编辑';
  MainForm.model = {
    id: row.id,
    name: row.name,
    addr: row.addr,
    fzr: row.fzr,
    phone: row.phone,
  };
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainSubmit = () => {
  MainFormRef.value.validate((valid) => {
    if (valid) {
      MainPopup.visible = false;
      if (MainPopup.type === '新增') {
        AddMain();
      } else if (MainPopup.type === '编辑') {
        EditMain();
      }
    }
  });
}
const AddMain = () => {
  MainApi({
    method: 'post',
    data: {
      ...MainForm.model,
      company: info.company,
      project: curProject.id,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    GetMainTable();
  });
}
const EditMain = () => {
  MainById({
    method: 'patch',
    id: MainForm.model.id,
    data: {
      ...MainForm.model,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    GetMainTable();
  });
}
const handleMainDelete = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除 ${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainApi({
      method: 'get',
      params: {
        parent: row.id,
      },
    }).then(res => {
      if (res?.results?.length) {
        ElMessage.error('请先删除子组织！');
        return;
      }
      MainById({
        method: 'delete',
        id: row.id,
      }).then(res => {
        ElMessage.success('删除成功');
        GetMainTable();
      });
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
</script>

<template>
  <div class="flex-column mainCard">
    <el-form label-width="120px" class="flex t_form">
      <el-form-item label="排序依据：">
        <el-select v-model="Filter.ordering" clearable >
          <el-option value="-create_time" label="按创建时间倒序"></el-option>
          <el-option value="create_time" label="按创建时间正序"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称查询：">
        <el-input v-model="Filter.search" clearable></el-input>
      </el-form-item>
    </el-form>
    <el-table :data="MainTable.data" row-key="id" default-expand-all scrollbar-always-on>
      <el-table-column label="组织名称" prop="name" min-width="250px" fixed="left"></el-table-column>
      <el-table-column label="负责人" prop="fzr_name" min-width="120px"></el-table-column>
      <el-table-column label="联系电话" prop="phone" min-width="120px"></el-table-column>
      <el-table-column label="地址" prop="addr" min-width="150px"></el-table-column>
      <el-table-column label="操作" fixed="right" min-width="280px">
        <template #default="scope">
          <el-button link type="primary" @click="handleMainAdd(RIGHT['304'], scope.row)" :disabled="!RIGHT['304']">
            新增下级
          </el-button>
          <template v-if="scope.row.id">
            <el-button link type="primary" @click="handleMainEdit(RIGHT['305'], scope.row)" :disabled="!RIGHT['305']">
              编辑
            </el-button>
            <el-button link type="danger" @click="handleMainDelete(RIGHT['306'], scope.row)" :disabled="!RIGHT['306']">
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
  
  <!-- 新增编辑 -->
  <el-dialog width="500px" :title="MainPopup.type + '组织'" v-model="MainPopup.visible">
    <el-form
      ref="MainFormRef"
      :model="MainForm.model"
      label-width="120px"
    >
      <el-form-item prop="name" label="组织名称：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="MainForm.model.name"></el-input>
      </el-form-item>
      <el-form-item prop="addr" label="地址：">
        <el-input v-model="MainForm.model.addr"></el-input>
      </el-form-item>
      <el-form-item class="tb" prop="fzr" label="负责人：">
        <el-select
          filterable
          remote
          remote-show-suffix
          :remote-method="getIuserList"
          v-model="MainForm.model.fzr"
          multiple
          collapse-tags
          collapse-tags-tooltip
          clearable
        >
          <el-option v-for="item in MainTable.iuserList" :value="item.id" :key="item.id" :label="item.truename"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="phone" label="联系电话：">
        <el-input v-model="MainForm.model.phone"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="MainPopup.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleMainSubmit()">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
</style>